import React , {Component} from 'react';
import { Avatar, Breadcrumb, Menu, Dropdown, Icon,Select, message, Layout} from 'antd';
import { Link } from 'react-router-dom';
import './index.less';
import axios from 'axios';
import { connect } from 'react-redux';
import Tips from '../../Tips/index'

const Option = Select.Option;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

class Head extends React.Component {
    constructor(){
        super()
        this.state={
            networkdata:[],
            orgiddata:[],
            userName: '',
            networknickname:'暂无网络',
            orgname:'暂无组织'
        }
    }
    componentWillMount(){
        var $this=this     
        this.ismounted=true
        setTimeout(()=>{
            $this.getData() 
            $this.setState({
                userName: localStorage.getItem("userName")
            }); 
        })
    }
    componentWillUnmount(){
        this.ismounted=false
    }
    
    logOut =()=>{
        this.props.dispatch({
            type: 'loginout'
        }) 
    }
        
    Sandboxc0 = () => {     
        localStorage.setItem('sandbox', 0)
        this.props.dispatch({
            type: 'changSandBox',
            changesand:0
        })      
        this.props.dispatch({
            type: 'changenetwork',
            network: ''
        })
        this.setState({
            networkdata: '',
            network: ''
        });     
    }
    Sandboxc1 = () => {
        localStorage.setItem('sandbox', 1)
        this.props.dispatch({
            type: 'changSandBox',
            changesand: 1
        }) 
        this.props.dispatch({
            type: 'changenetwork',
            network: ''
        })
        this.setState({
            networkdata: '',
            network: ''
        });      
    }

    sandbox = (
        <Menu   >
            <Menu.Item key="0" disabled={false}  >
                <a onClick={this.Sandboxc0} >沙盒环境（SAND）</a>
            </Menu.Item>
            <Menu.Item key="1" disabled  >
                生产环境（PROD）           
        </Menu.Item>
        </Menu>
    );
    personMenu = (
            <Menu>
                <Menu.Item key="0">
                    <Link to="/changePassword"><span>密码修改</span></Link>
                </Menu.Item>
                <Menu.Item key="1">
                    <Link to="/changePhone"><span>手机修改</span></Link>
                </Menu.Item>
                <Menu.Item key="2">
                    <span onClick={this.logOut}>退出登录</span>
                </Menu.Item>
            </Menu>
    ); 


    changenetwork=(ev,name)=>{  
        if(!name){
            name=ev.item.props.children
        }
        if (typeof ev != 'string' && typeof ev != 'number' && ev != undefined){ ev = ev.key }
        localStorage.setItem('orgnet', JSON.stringify({ org: this.props.changeOrgid, net: ev }))
        this.props.dispatch({
            type:'changenetwork',
            network:ev
        })    
    }
    componentWillUpdate(nextprops){
        if(nextprops.updateNet&&nextprops.changeOrgid){
            if(nextprops.updateNet){
                this.props.dispatch({
                    type: 'updatenet',
                    onoff: false
                })  
            }
            setTimeout(()=>{
                const $this=this
                const Token = localStorage.getItem('token');
                axios({
                    method: 'get',
                    url: '/api/block/network/queryNetWorkName?token=' + Token,
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: Token
                    },
                    params: { orgId: nextprops.changeOrgid }
                })
                .then(function (response) {
                    if($this.ismounted){
                    setTimeout(() => {
                        if (response.data[0]) {
                            $this.changenetwork(response.data[0].networkName, response.data[0].nickname)
                            $this.setState({
                                networkdata: response.data,
                                network: response.data[0].nickname
                            });
                            $this.props.dispatch({
                                type: 'netOrg',
                                net: response.data
                            })
                        } else {
                            $this.props.dispatch({
                                type: 'netOrg',
                                net: ''
                            })
                            $this.props.dispatch({
                                type: 'changenetwork',
                                network: ''
                            })
                            $this.setState({
                                networkdata: '',
                                network: '',
                            });
                        }
                    });
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
            })
        }
    }
    changeorgid=(ev,name,orgData = this.state.orgiddata)=>{
        var $this = this;
        let newOrgData = ""; 
        if (!name) {
            name = ev.item.props.children
        }
        const Token = localStorage.getItem('token');
        if (typeof ev != 'string' && typeof ev != 'number' && ev != undefined) ev = ev.key
        if(orgData){
           orgData.forEach((e,i)=>{
               if(e.id == ev){
                   newOrgData = e
               }
           })  
        }
        this.props.dispatch({
            type: 'changeorgid',
            orgid: ev
        })
        localStorage.setItem('orgnet', JSON.stringify({ org: ev, net: '' }))
        this.props.dispatch({
            type: 'orgdata',
            orgData: newOrgData
        })
        this.props.dispatch({
            type: 'changenetwork',
            network: ''
        })
        this.setState({
            networkdata: '',
            network: ''
        });
        this.setState({
            orgid : ev,
            orgname: name,
        });
        axios({
            method: 'get',
            url : '/api/block/network/queryNetWorkName?token='+Token,
            headers:{
                'Content-Type':'application/json',
                Authorization:Token
            },
            params: {orgId:ev}
        })
        .then(function (response) {
            if($this.ismounted){
            setTimeout(() => {
                if(response.data[0]){
                    const oldnet = JSON.parse(localStorage.getItem('orgnet')) ? JSON.parse(localStorage.getItem('orgnet')) : {}
                    var num = 0
                    response.data.forEach((e, i) => {
                        if (e.networkName == oldnet.net) {
                            num = i
                        }
                    })
                    $this.changenetwork(response.data[num].networkName, response.data[num].nickname)
                    $this.setState({
                        networkdata: response.data,
                        network: response.data[num].nickname
                    }); 
                    $this.props.dispatch({
                        type: 'channelId',
                        channelid: 'mychannel',
                    })
                    $this.props.dispatch({
                        type: 'netOrg',
                        net: response.data
                    })
                }else{
                    $this.props.dispatch({
                        type: 'netOrg',
                        net: ''
                    })
                    $this.props.dispatch({
                        type: 'changenetwork',
                        network: ''
                    })
                    $this.props.dispatch({
                        type: 'channelId',
                        channelid: 'mychannel',
                    })
                    $this.setState({
                        networkdata: '',
                        network: '',
                    });
                }           
            }); 
        }                
        })
        .catch(function (error) {

        console.log(error);
        });        
    }
    getData=()=>{
        var $this=this  
            const Token = localStorage.getItem('token');
            setTimeout(()=>{
                axios({
                    method: 'get',
                    url : '/api/customer/baasorg/org/all',
                    headers:{
                        'Content-Type':'application/json',
                        Authorization:Token
                    },
                })
                .then(function (response) {
                    if($this.ismounted){
                        if ( response.data && response.data.data && response.data.data.rows[0] ){
                            const oldorg = JSON.parse(localStorage.getItem('orgnet')) ? JSON.parse(localStorage.getItem('orgnet')):{}
                            var num=0
                            response.data.data.rows.forEach((e,i)=>{
                                if(e.id==oldorg.org){
                                    num=i
                                }
                            })
                            $this.setState({
                                orgiddata: response.data.data.rows,
                                orgid : response.data.data.rows[num].orgName
                            });
                            $this.props.dispatch({
                                type:'orgNet',
                                org: response.data.data.rows
                            })
                            $this.changeorgid(response.data.data.rows[num].id, response.data.data.rows[num].orgName, response.data.data.rows)    
                        }                   
                    }                                                            
                })
                .catch(function (error) {
                console.log(error);
                });   
            }) 
    }


	render() {     
        var networkList = ''
        let networkname = this.props.changeNetwork, orgname = this.props.changeOrgid
        if(this.state.networkdata.length!==0){
            networkList=this.state.networkdata.map((e,i)=>{
                if (e.networkName == networkname) networkname=e.nickname
                return (
                    <Menu.Item key={e.networkName} >{e.nickname}</Menu.Item>
                )
            })
        }else{
            networkname = '暂无网络'
            networkList = (<Menu.Item disabled >暂无网络</Menu.Item>)
        }
        var orgidList = ''
        if(this.state.orgiddata.length!==0){
            orgidList=this.state.orgiddata.map((e,i)=>{
                if (orgname == e.id) orgname = e.orgName
                return (<Menu.Item key={e.id} >{e.orgName}</Menu.Item>)
            })
        }else{
            orgname ='暂无组织'        
            orgidList = (<Menu.Item disabled >暂无组织</Menu.Item>)
        }

		return (
            <div className="clearfix">
                <Dropdown overlay={this.sandbox} trigger={['click']}>
                    <a className="ant-dropdown-link" href="#">
                        <p className='text'>生产环境（PROD）</p>
                        <Icon type="down" />
                    </a>
                </Dropdown>
                <Dropdown  className="accountlist" overlay={this.personMenu} trigger={['click']} >
                    <a className="ant-dropdown-link-u txt" href="#">
                    <div className="DropdownItem DropItem3">
                        <p className='text'>{this.state.userName}</p>
                        <Icon type="down" />
                        </div> 
                    </a>              
                </Dropdown>

                <div className="DropdownItem DropItem1">
                    
                    <Dropdown overlay={(<Menu onClick={this.changenetwork}   >{networkList}</Menu>)} trigger={['click']} >
                        <a className="ant-dropdown-link" href="#">
                            <p className='textp'>网络: </p> 
                            <p className='textcontent'>{networkname} </p>
                            <Icon type="down" />
                        </a>
                    </Dropdown> 

                 </div>  
                        <div className="DropdownItem DropItem2">
                           
                    <Dropdown overlay={(<Menu onClick={this.changeorgid} >{orgidList}</Menu>)} trigger={['click']} >
                        <a className="ant-dropdown-link" href="#">
                            <p className='textp'>组织: </p> 
                            <p className='textcontent'>{orgname} </p>
                            <Icon type="down" />
                        </a>
                    </Dropdown>             

                    
                        </div>     

            </div>
		);
	}
}


export default connect((state)=>{
    return {...state};
    })(Head);
